import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution406 {
    public int[][] reconstructQueue(int[][] people) {
        Arrays.sort(people, (p1, p2) -> {
            long p10 = p1[0], p11 = p1[1], p20 = p2[0], p21 = p2[1];
            if(p10 == p20){
                return (int)(p11 - p21);
            }
            return (int)(p20 - p10);
        });
        List<int[]> res = new ArrayList<>();
        for (int[] p : people) {
            int tmpK = p[1];
            if(res.size() <= tmpK){
                res.add(p);
            }
            else{
                res.add(tmpK, p);
            }
        }
        return res.toArray(new int[][]{});
    }

    public static void main(String[] args) {
        Solution406 s = new Solution406();
        s.reconstructQueue(new int[][]{new int[]{7,0}, new int[]{4,4}, new int[]{7,1}, new int[]{5,0}, new int[]{6,1}, new int[]{5,2}});
    }
}
